package main

import (
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"reflect"
	"test/model"
	"time"

	"github.com/liudng/godump"
)

type User struct {
	ID        uint
	Name      string
	Age       string
	CreatedAt time.Time
	UpdatedAt time.Time
}

/* var (
	//变量db 通过init直接初始化
	dbvar  *gorm.DB
	err    error
	dbinfo string
) */

/* func init() {
	//拼接数据库连接信息
	dbinfo = fmt.Sprintf("%s:%s@(%s:%s)/%s?charset=utf8&parseTime=True&loc=Local", dbuser, dbpassword, dbip, dbport, database)
	//初始化db
	db, err = gorm.Open("mysql", dbinfo)
	if err != nil {
		fmt.Println("mysql打开失败", err)
		return
	}
	//创建表关联user结构体
	db.AutoMigrate(&User{})
} */

func AddUser(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	fmt.Println(r.Form) //name := r.FormValue("name")
	//age := r.FormValue("age")
	name := r.Form["name"][0]
	age := r.Form["age"][0]
	godump.Dump(name)
	godump.Dump(age)
	db := model.Conn()
	user := User{Name: name, Age: age}

	result := db.Create(&user) // 通过数据的指针来创建
	if result.Error != nil {
		println(result.Error)
	}
	if result.RowsAffected > 0 {
		fmt.Fprintf(w, "插入成功")
	}
}
func UpdateUser(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	fmt.Println(r.Form)
	fmt.Println("method:", r.Method) //获取请求的方法
	name := r.FormValue("name")
	age := r.FormValue("age")
	id := r.FormValue("id")

	db := model.Conn()
	user := User{Name: name, Age: age}

	res := db.Model(&user).Where("id = ?", id).Updates(User{Name: name, Age: age})

	fmt.Println("update succ:", res.RowsAffected)
}

func DelUser(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	fmt.Println(r.Form)
	fmt.Println("method:", r.Method) //获取请求的方法
	name := r.FormValue("name")
	age := r.FormValue("age")
	id := r.FormValue("id")

	db := model.Conn()
	user := User{Name: name, Age: age}

	res := db.Model(&user).Where("id = ?", id).Updates(User{Name: name, Age: age})

	fmt.Println("update succ:", res.RowsAffected)
}

func UserList(w http.ResponseWriter, r *http.Request) {
	db := model.Conn()
	var user []User
	//var user []User
	fmt.Println(reflect.TypeOf(user))
	db.AutoMigrate(&User{})
	//var users []User
	/* result := map[string]interface{}{}

	db.Debug().Model(&user).Find(&result)
	fmt.Printf("user:%#v\n", result) */
	db.Debug().Find(&user)

	result, err := json.Marshal(user)
	if err != nil {
		fmt.Println(err)
	}
	w.Write(result)
	// jsonStringData := string(result)
	// godump.Dump(jsonStringData)
}

func sayhelloName(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "Hello world!") //这个写入到 w 的是输出到客户端的
}

func main() {
	http.HandleFunc("/", sayhelloName)         //设置访问的路由
	http.HandleFunc("/adduser", AddUser)       //设置访问的路由
	http.HandleFunc("/updateuser", UpdateUser) //设置访问的路由
	http.HandleFunc("/deluser", DelUser)       //设置访问的路由
	http.HandleFunc("/listuser", UserList)     //设置访问的路由
	err := http.ListenAndServe(":9090", nil)   //设置监听的端口
	if err != nil {
		log.Fatal("ListenAndServe: ", err)
	}
}
